<!--
禁止修改!此文件是产品代码的一部分，后续可能变更或者不再开放。
若有问题，请参考前端相关二开文档。
-->
<template>
  <div :class="prefixCls">
    <h3-report
      v-if="loaded"
      :class="[`${prefixCls}`]"
      :reportId="objectId"
      :corpId="corpId"
      :config="config"
      :limit="{ list: { dimension: 50 } }"
      :isAdmin="false"
      @drillDown="onDrillDown"
    />

    <IframeModal
      :showIframeForm="showIframeForm"
      :IframeFormUrl="IframeFormUrl"
      @close="closeModal"
    />
  </div>
</template>

<script lang="ts">
import { listApi } from 'cloudpivot/api';
import { DashboardPro } from '@h3/report';
import { Component, Vue, Watch } from 'vue-property-decorator';
import ReportOptions from '@h3/report/dist/options';
import * as platform from 'cloudpivot-platform/platform';

import IframeModal from 'cloudpivot-flow/flow-center/src/components/pc/components/iframe-modal/iframe-modal.vue';

@Component({
  name: 'app-report',
  components: {
    H3Report: DashboardPro,
    IframeModal,
  },
  // beforeRouteEnter(to, from, next) {
  //   next(vm => {
  //     (vm as AppReport).load();
  //   });
  // },
  // beforeRouteUpdate(to, from, next) {
  //   next();

  //   const vm = this as AppReport;
  //   vm.load();
  // }
})
export default class AppReport extends Vue {
  prefixCls = 'report';

  title = '';

  corpId = 'a';

  objectId = '';

  loaded = false;

  mounted() {
    ReportOptions.jumpDashboard.getJumpUrl = customFunction;
    function customFunction(dashboardItem) {
      const jumpUrl = `${ReportOptions.baseUrl}/jump-report/${dashboardItem.options.appCode}/${dashboardItem.options.code}`;
      // 生成链接的逻辑是集成方定义
      return jumpUrl;
    }

    window.addEventListener('message', this.reloadMessage, false);
  }

  get reportCode() {
    return this.$route.params.reportCode;
  }

  get appCode() {
    return this.$route.params.appCode;
  }

  get token() {
    return localStorage.getItem('token');
  }

  get config() {
    return {
      token: this.token,
      reportCode: this.reportCode,
      appCode: this.appCode,
    };
  }

  load() {
    this.loaded = false;
    const closeLoad = (this.$message as any).loading();
    const shortName = this.$store.state.themsConfig.name;
    const frontTitle = shortName || '奥哲云枢';

    listApi
      .getReport({
        code: this.reportCode,
        mobile: false,
      })
      .then(
        (res: any) => {
          closeLoad();
          if (res.errcode === 0) {
            this.objectId = res.data.reportObjectId || '';
            const name_i18n = res.data.name_i18n
              ? JSON.parse(res.data.name_i18n)
              : {};

            const modalName = name_i18n[this.$i18n.locale] || res.data.name;

            document.title = `${frontTitle}-${modalName}` || `${frontTitle}`;
          } else {
            this.$message.error(res.errmsg, 3);
            document.title = `${frontTitle}`;
          }
          platform.service.setTitle(document.title);
        },
        () => closeLoad(),
      )
      .finally(() => (this.loaded = true));
  }

  @Watch('reportCode', {
    immediate: true,
  })
  onReportCodeChange() {
    if (this.reportCode) {
      this.load();
    }
  }

  showIframeForm = false;

  IframeFormUrl = '';

  async onDrillDown(...args: any[]) {
    const { id, tableName } = args[0];
    if (id && tableName) {
      const schemaCode = tableName.substring(tableName.indexOf('_') + 1);
      const params = {
        schemaCode,
        bizObjectId: id,
      };
      const res = await listApi.getFormUrl(params);
      if (typeof res === 'string') {
        const url = res;
        if (url) {
          // window.open(url);
          if (platform.IS_DINGTALK) {
            this.$router.push(url).catch((err: any) => {
              console.log(err);
            });
          } else {
            // window.open(url);
            this.showIframeForm = true;
            this.IframeFormUrl = url;
          }
        }
      } else if (typeof res === 'object' && !res.errcode) {
        return this.$message.error(res.errmsg as string, 3);
      } else {
        return this.$message.error('获取表单链接失败', 3);
      }
    }
  }

  closeModal() {
    this.showIframeForm = false;
    this.IframeFormUrl = '';
  }

  reloadMessage(event: any) {
    if (event.data === 'hidden-close') {
      this.showIframeForm = false;
      this.IframeFormUrl = '';
    }
    if (event.data === 'reload-close') {
      this.showIframeForm = false;
      this.IframeFormUrl = '';
      return;
    }
    if (event.data === 'reload') {
      return;
    }
    if (event.source === window) {
      return;
    }
    if (
      event.data.indexOf('/application') !== -1 ||
      event.data.indexOf('%2Fapplication') !== -1
    ) {
      this.showIframeForm = false;
      this.IframeFormUrl = '';
    }
  }

  destroyed() {
    window.removeEventListener('message', this.reloadMessage, false);
  }
}
</script>

<style lang="less" scoped>
.report {
  height: 100%;
}
</style>
